/*
 * File Name:               EventDispatcher.cs
 *
 * Description:             简易事件分发工具
 * *                        T 建议使用 枚举 或 int 类型
 * *                        使用可变参数的优势是使用方便
 * *                        劣势是在处理值类型参数时会有额外的装箱操作
 * Author:                  lisiyu
 * Create Date:             2016/11/18
 */

using System;
using System.Collections.Generic;

public class XEventDispatcher<T> : ICache where T : struct
{
    public Dictionary<T, Action<object[]>> mHandlers;

    public XEventDispatcher()
    {
        mHandlers = new Dictionary<T, Action<object[]>>();
    }

    public void onSpawn(object args)
    {
        // nothing to do
    }

    public void onRecycle()
    {
        mHandlers.Clear();
    }

    public void addListener(T msgId, Action<object[]> callback)
    {
        if (mHandlers.ContainsKey(msgId))
        {
            mHandlers[msgId] += callback;
        }
        else
        {
            mHandlers.Add(msgId, callback);
        }
    }

    public void removeListener(T msgId, Action<object[]> callback)
    {
        if (mHandlers.ContainsKey(msgId))
        {
            mHandlers[msgId] -= callback;
            if (mHandlers[msgId] == null)
                mHandlers.Remove(msgId);
        }
    }

    public void dispatch(T msgId, params object[] args)
    {
        if (!mHandlers.ContainsKey(msgId))
            return;

        mHandlers[msgId](args);
    }
}